package com.goldcn.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;

import com.goldcn.config.TokenConstants;
import com.goldcn.enums.ErpInterfaceCfgEnum;
import com.goldcn.enums.RoleCodeEnum;
import com.goldcn.enums.SmsTempEnum;
import com.goldcn.enums.TopDeptEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.ErpDto.MemberDto;
import com.goldcn.user.ErpDto.ResultData;
import com.goldcn.user.dao.*;
import com.goldcn.user.dto.*;
import com.goldcn.user.model.*;
import com.goldcn.user.vo.*;
import com.goldcn.util.*;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 1111 on 2016/11/8.
 */
@Service
@Transactional
@ConfigurationProperties(prefix = "sms")
public class UserInfoService {

    private String codeUrl;
    private String openImcs;
    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserLoginMapper userLoginMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Autowired
    BankCardMapper bankCardMapper;

    @Autowired
    OrganizationalMapper organizationalMapper;

    @Autowired
    UserApplyMapper userApplyMapper;

    @Autowired
    UserTransferMapper userTransferMapper;

    @Autowired
    RoleService roleService;
    @Autowired
    UserTransferService userTransferService;

    @Autowired
    FeedbackMapper feedbackMapper;

    @Autowired
    CountMapper countMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    CountService countService;




    @Autowired
    RedisService redisService;

    @Autowired
    ConfigService configService;
    @Autowired
    OrganizationalService organizationalService;

    @Autowired
    ErrErpBaseMapper errErpBaseMapper;

    @Autowired
    CompanyInfoMapper companyInfoMapper;


    private Logger logger = Logger.getLogger(UserInfoService.class);

    public void setCodeUrl(String codeUrl) {
        this.codeUrl = codeUrl;
    }

    /**
     * 验证手机验证码
     */
    public Object verifyMobileCode(String mobile, String code) {
        String url = codeUrl + mobile;
        JSONObject json = restTemplate.getForObject(url, JSONObject.class);
        if (json.size() == 0) {
            throw new ServiceException("手机验证码错误", RestConst.ErrorCode.SERVICE_LOGINERROR);
        } else {
            String getCode = json.get(mobile).toString();
            if (!code.equals(getCode)) {
                throw new ServiceException("手机验证码错误", RestConst.ErrorCode.SERVICE_LOGINERROR);
            }
        }

        return 1;
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Object addUserInfoV2(RegisterDto registerDto) throws Exception {

        // 当添加系统管理员和销售经理的时候 要验证他的添加人信息
        if (registerDto.getAddUser() != null && !registerDto.getAddUser().equals("")) {
            UserInfo userInfo = selectByAccount(registerDto.getAddUser(), SystemContext.getCompanyID());
            if (userInfo == null) {
                throw new ServiceException("未查到添加人信息，无权操作", RestConst.ErrorCode.FORM_FAIL);
            }
            if (userInfo.getType() != 1 && userInfo.getType() != 2) {
                throw new ServiceException("添加人没有权限进行操作", RestConst.ErrorCode.FORM_FAIL);
            }
        } else {
            //验证验证码
            verifyMobileCode(registerDto.getLoginName(), registerDto.getMobileCode());
        }

        PrivateKey key = (PrivateKey) redisService.loadKey(registerDto.getRasId());
        byte[] en_result = RSAUtils.hexStringToBytes(registerDto.getPassWord());
        byte[] de_result = RSAUtils.decrypt(key, en_result);
        StringBuffer sb = new StringBuffer();
        sb.append(StringUtils.newStringUtf8(de_result));
        registerDto.setPassWord(CommonUtils.MD5(sb.reverse().toString()));
        UserInfo userInfo = new UserInfo();
        userInfo.setAccount(registerDto.getLoginName());
        userInfo.setMobile(registerDto.getPhone());
        userInfo.setPassWord(registerDto.getPassWord());
        userInfo.setType(registerDto.getType());
        userInfo.setName(registerDto.getName());
        userInfo.setOrganizationalID(selectByAccount(registerDto.getAddUser(), SystemContext.getCompanyID()).getOrganizationalID());
        userInfo.setIsAdmin(Objects.equal(registerDto.getType(), 1) ? 1 : 2);
        Object user = addUserInfo(userInfo);
        return user;
    }


    // @Transactional( rollbackFor = RuntimeException.class)
    //
    public Object addUserInfo(UserInfo userInfo) {
        //1系统管理人员 2销售经理  4会员 5供应商
        //除了会员注册之外 其他的都会有account和mobile信息
        if (userInfo.getAccount() == null) { //如果账户为空，则填手机号
            userInfo.setAccount(userInfo.getMobile());
        }
        userInfo.setCompanyID(SystemContext.getCompanyID());

        //1系统管理人员 2销售经理 3销售顾问 4会员 5供应商
        int type = userInfo.getType();
        switch (type) {
            case 1:
                //系统管理员  account/mobile都是不同的  切只生成一个userInfo和一个login信息
                //由于account和mobile都是存在的因此 只需要验证account是否存在就可以了
                UserInfo ui1Info = userInfoMapper.selectByAccount(userInfo.getAccount(), userInfo.getCompanyID());
                if (ui1Info != null) {
                    throw new ServiceException(userInfo.getAccount() + "该账户已经存在", RestConst.ErrorCode.FORM_FAIL);
                }
                break;
            case 2:
                //作为理财经理进来 其实跟上面是一致得  但是 而且也只需要验证userInfo的account是否存在了
                UserInfo ui2Info = userInfoMapper.selectByAccount(userInfo.getAccount(), userInfo.getCompanyID());
                UserLogin loginAccount = userLoginMapper.selectLoginName(userInfo.getAccount(), userInfo.getCompanyID());
                if (ui2Info != null || loginAccount != null) {
                    throw new ServiceException(userInfo.getAccount() + "该账户已经存在", RestConst.ErrorCode.FORM_FAIL);
                }
                String mobile = userInfo.getMobile();
                if (mobile == null || "".equals(mobile)) {
                    throw new ServiceException(userInfo.getAccount() + "电话号码不能为空", RestConst.ErrorCode.FORM_FAIL);
                }
                //搜索登录表 看一下 mobile和account是否已经存在登录表中了
               /* UserLogin loginMobile = userLoginMapper.selectLoginName(mobile,userInfo.getCompanyID());
                if (loginMobile != null) {
                    throw new ServiceException(userInfo.getMobile() + "电话号码已经被注册过", RestConst.ErrorCode.FORM_FAIL);
                }*/
                break;
            case 4:
                //只需要验证会员的电话号码就可以 如果说是
                UserInfo ui4Info = userInfoMapper.selectByAccount(userInfo.getAccount(), userInfo.getCompanyID());
                UserLogin ui4LoginMobile = userLoginMapper.selectLoginName(userInfo.getAccount(), userInfo.getCompanyID());
                if (ui4Info != null || ui4LoginMobile != null) {
                    throw new ServiceException(userInfo.getAccount() + "该账户已经存在", RestConst.ErrorCode.FORM_FAIL);
                }
                break;
            case 5: //供应商也是用账户和电话都是可以登录的
                UserInfo ui5Info = userInfoMapper.selectByAccount(userInfo.getAccount(), userInfo.getCompanyID());
                UserLogin ui5LoginAccount = userLoginMapper.selectLoginName(userInfo.getAccount(), userInfo.getCompanyID());
                if (ui5Info != null || ui5LoginAccount != null) {
                    throw new ServiceException(userInfo.getAccount() + "该账户已经存在", RestConst.ErrorCode.FORM_FAIL);
                }
                UserLogin ui5LoginMobile = userLoginMapper.selectLoginName(userInfo.getMobile(), userInfo.getCompanyID());
                if (ui5LoginMobile != null) {
                    throw new ServiceException(userInfo.getMobile() + "该手机号已被注册", RestConst.ErrorCode.FORM_FAIL);
                }
                break;
            default:
                throw new ServiceException("用户注册类型错误", RestConst.ErrorCode.FORM_FAIL);
        }

        if (userInfo.getUserID() == null || userInfo.getUserID() == 0L) {
            userInfo.setUserID(IdGen.get().nextId());
        }

        if (userInfo.getType() == 2) {  //如果是添加员工，则默认未审核
            userInfo.setIsStop(2);
        } else {
            userInfo.setIsStop(0);
        }
        userInfo.setAddTime(CommonUtils.getCurTimestamp());
        userInfo.setUpdateTime(CommonUtils.getCurTimestamp());
        userInfo.setCompanyID(SystemContext.getCompanyID());
        userInfo.setState(0);

        insertSelective(userInfo);

        if (userInfo.getType() == 2) {  //如果是销售经理则生成会员顾问统计表和订单统计表 赋予销售经理的角色
            UserRole userRole = new UserRole();
            userRole.setID(IdGen.get().nextId());
            userRole.setUserID(userInfo.getUserID());
            userRole.setRoleID(organizationalService.getRole(SystemContext.getCompanyID(), RoleCodeEnum.EMPLOYEE.getCode()).getRoleID());
            userRoleMapper.insert(userRole);
            //获取用户生产统计表所需组织信息
            UserCountDto userCountDto = getOInfoForCount(userInfo.getUserID());
            userCountDto.setSalesManagerID(userInfo.getUserID());

            Count count = new Count();
            count.setBranchID(userCountDto.getBranchID());
            count.setTwoLevelBranchID(userCountDto.getTwoLevelBranchID());
            count.setSubbranchID(userCountDto.getSubbranchID());
            count.setSalesManagerID(userInfo.getUserID());

            countService.addCount(count); //插入会员顾问统计表
            DataResult result = HttpUtil.httpPost(ProConstants.operateOrderCount, userCountDto, restTemplate);
            if (result.getIsSuccess() != 1) {
                throw new ServiceException("生成订单统计表失败,调用bank服务出错", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }

        //登录表保存相关信息
        UserLogin userLogin = new UserLogin();
        userLogin.setUserID(userInfo.getUserID());
        userLogin.setPassWord(userInfo.getPassWord());
        userLogin.setCompanyID(SystemContext.getCompanyID());

        //upadte 修改供应商不能登录APP H5且能注册会员或员工 2017年6月26日  buyadong   del || userInfo.getType() == 5
        if (userInfo.getType() == 2) {
            //如果是理财经理 则帮他生成两条登录数据
            if (userInfo.getAccount() != null) {
                userLogin.setId(IdGen.get().nextId());
                userLogin.setLoginName(userInfo.getAccount());
                userLoginMapper.insertSelective(userLogin);
            }
            if (userInfo.getMobile() != null) {
                if (!userInfo.getMobile().equals(userInfo.getAccount())) {
                    userLogin.setId(IdGen.get().nextId());
                    userLogin.setLoginName(userInfo.getMobile());
                    userLoginMapper.insertSelective(userLogin);
                }
            }
        } else {
            userLogin.setId(IdGen.get().nextId());
            userLogin.setLoginName(userInfo.getAccount());
            userLoginMapper.insertSelective(userLogin);
            //add 中银金行添加判断 如果是管理员则添加电话登录
            if (userInfo.getType() == 1) {
                Integer isMobileLogin = CommonTools.getExtInt(restTemplate, "isMobileLogin");
                if (null != isMobileLogin && isMobileLogin == 1) {
                    if (!userInfo.getMobile().equals(userInfo.getAccount())) {
                        userLogin.setId(IdGen.get().nextId());
                        userLogin.setLoginName(userInfo.getMobile());
                        UserLogin userLogin1 = userLoginMapper.selectLoginName(userInfo.getMobile(), SystemContext.getCompanyID());
                        if (userLogin1 != null) {
                            throw new ServiceException("手机号已被注册，请换一个手机号");
                        }
                        userLoginMapper.insertSelective(userLogin);
                    }
                }
            }

            //会员送金豆 100 unit added by pengzh 2018-4-8
            if (userInfo.getType() == 4) {
                setManagerPoint(userInfo);
            }
        }
        //这里的设计是 如果是管理员 app/H5 应该都只是添加一条数据
//        if (userInfo.getAccount().equals(userInfo.getMobile())) {
//            userLogin.setId(IdGen.get().nextId());
//            userLogin.setLoginName(userInfo.getAccount());
//            userLoginMapper.insertSelective(userLogin);
//        } else {
//            if (userInfo.getAccount() != null) {
//                userLogin.setId(IdGen.get().nextId());
//                userLogin.setLoginName(userInfo.getAccount());
//                userLoginMapper.insertSelective(userLogin);
//            }
//            if (userInfo.getMobile() != null) {
//                userLogin.setId(IdGen.get().nextId());
//                userLogin.setLoginName(userInfo.getMobile());
//                userLoginMapper.insertSelective(userLogin);
//            }
//        }


        //会员抛转到erp
        if (userInfo.getType() == 4) {
            // sendToErp(userInfo,0); //0新增1修改
        }

        return userInfo.getUserID();
    }


    private Object sendToErp(UserInfo userInfo, int type) {
        if (!configService.isOpenErp()) {
            return "success";
        }
        try {
            int i = addOrUpdateMemberForErp(userInfo, type);
            if (i != 1) {
                throw new ServiceException("修改会员信息失败", RestConst.ErrorCode.FORM_FAIL);
            }
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //异常发送手机号码
            jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
            jsonObject.put("param", new String[]{"修改会员对接ERP失败:会员ID为" + userInfo.getUserID()});
            DataResult resultSms = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
            if (resultSms.getIsSuccess() != 1) {
                logger.info("发送短信失败");
            }
            logger.info("修改会员信息失败:" + userInfo.getUserID() + ":" + userInfo.getName() + "--开始插入错误表信息");
            ErrErpBase errErpBase = errErpBaseMapper.selectByInfoId(userInfo.getUserID());
            if (errErpBase == null) {
                errErpBase = new ErrErpBase();
                errErpBase.setErrorId(IdGen.get().nextId());
                errErpBase.setInfoId(userInfo.getUserID());
                errErpBase.setAddTime(System.currentTimeMillis());
                errErpBase.setType("2");//0供应商1组织2会员
                errErpBaseMapper.insertSelective(errErpBase);
            } else {
                errErpBase.setErrorId(IdGen.get().nextId());
                errErpBase.setInfoId(userInfo.getUserID());
                errErpBase.setAddTime(System.currentTimeMillis());
                errErpBase.setType("2");
                errErpBaseMapper.updateByPrimaryKeySelective(errErpBase);
            }
            logger.info("插入信息表成功");
        }
        return userInfo.getUserID();
    }

    public static Long dateToStamp(String s) throws java.text.ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = null;
        if (s.contains("-")) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        } else if (s.contains(".")) {
            simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
        }
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
    }

    private int addOrUpdateMemberForErp(UserInfo info, int type) {
        MemberDto memberDto = new MemberDto();
        memberDto.setMemberID(info.getUserID() + "");
        memberDto.setShopID("0");
        memberDto.setName(info.getName());
        memberDto.setPhone(info.getMobile());
        memberDto.setNickname(info.getNickName());
        memberDto.setSex(info.getSex());
        memberDto.setBuildDate(info.getAddTime());
        try {
            if (CommonUtils.isNotEmpty(info.getBirthday())) {
                memberDto.setBirthday(dateToStamp(info.getBirthday()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        memberDto.setBirthdayType(0);
        memberDto.setSource(1);
        memberDto.setState(0);
        memberDto.setIntegral(0);
        memberDto.setIsJoint(1);
        memberDto.setAccountCode(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("secretKey", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
        RestTemplate ts = new RestTemplate();
        ResponseEntity<ResultData> result = null;
        HttpEntity<MemberDto> entity = new HttpEntity<MemberDto>(memberDto, headers);
        if (0 == type) {
            //表示新增
            result = ts.exchange(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDMEMBERURL.getCode()), HttpMethod.POST, entity, ResultData.class, "");
        } else {
            result = ts.exchange(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.UPDATEMEMBERURL.getCode()), HttpMethod.POST, entity, ResultData.class, "");
        }
        ResultData res = result.getBody();
        String code = res.getCode();
        if ("1".equals(code)) {
            //成功
            return 1;
        } else {
            return 0;
        }
    }


    public void insertSelective(UserInfo record) {
        userInfoMapper.insertSelective(record);
        try {
            if (Objects.equal(openImcs, "1")) {
                logger.info("====================================注册环信start========================================================");
                Hxuser hxuser = new Hxuser(record.getUserID() + "", record.getNickName());
                DataResult dataResult = HttpUtil.httpPost(ProConstants.addHxusers, Lists.newArrayList(hxuser), restTemplate);
                if (!Objects.equal(dataResult.getIsSuccess(), 1)) {
                    DataResult dataResult2 = HttpUtil.httpPost(ProConstants.addHxusers, Lists.newArrayList(hxuser), restTemplate);
                    if (!Objects.equal(dataResult2.getIsSuccess(), 1)) {
                        HttpUtil.httpPost(ProConstants.addHxusers, Lists.newArrayList(hxuser), restTemplate);
                    }
                }
                logger.info("====================================注册环信end========================================================");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            logger.error(e.getMessage());
        }
    }

    //修改用户信息
    public String updateUserInfo(UserInfo userInfo, boolean onlyResetPwd) {
        UserInfo ui = userInfoMapper.selectByPrimaryKey(userInfo.getUserID());
        if (onlyResetPwd) {
            String passWord = userInfo.getPassWord();
            if (passWord != null) {
                List<UserLogin> ulList = userLoginMapper.selectByUserID(userInfo.getUserID());
                for (UserLogin ul : ulList) {
                    ul.setPassWord(passWord);
                    userLoginMapper.updateByPrimaryKeySelective(ul);
                }
            }
            userInfoMapper.updateByPrimaryKeySelective(userInfo);

            return "success";
        }

        userInfo.setUpdateTime(ui.getUpdateTime());
        userInfo.setAccount(ui.getAccount());
        userInfo.setType(ui.getType());
        userInfo.setRecommendNO(ui.getRecommendNO());
        userInfo.setOrganizationalID(ui.getOrganizationalID());
        userInfo.setAddTime(ui.getAddTime());


        if (userInfo.getMobile() != null && !"".equals(userInfo.getMobile())) {
//            if (ui.getType() == 1 || ui.getType() == 2) {
            if (ui.getType() == 2) { //只有员工才能修改自己的手机号

                List<UserInfo> userInfo1s = userInfoMapper.selectByPhone(userInfo.getMobile(), ui.getCompanyID());
                if (userInfo1s != null && userInfo1s.size() != 0) {
                    throw new ServiceException("该手机号已存在，请换其他手机号", RestConst.ErrorCode.SERVICE_LOGINERROR);
                }
//                UserLogin userLogin = userLoginMapper.selectLoginName(userInfo.getMobile());//验证是否其他人用了这个手机号作为登录账号
//                if (userLogin != null) {
//                    throw new ServiceException("该手机号已存在，请换其他手机号", RestConst.ErrorCode.SERVICE_LOGINERROR);
//                }
            } else {
                userInfo.setMobile(ui.getMobile());
            }
        }
        String passWord = userInfo.getPassWord();
        if (passWord != null) {
            List<UserLogin> ulList = userLoginMapper.selectByUserID(userInfo.getUserID());
            for (UserLogin ul : ulList) {
                ul.setPassWord(passWord);
                userLoginMapper.updateByPrimaryKeySelective(ul);
            }
        }
        userInfoMapper.updateByPrimaryKeySelective(userInfo);

        if (userInfo.getType() == 4) {
            //sendToErp(userInfo,1);//修改会员信息抛转到erp
        }

        return "success";
    }

    private Boolean auditDept(UserInfo userInfo, StateDto stateDto) {
        if (Objects.equal(userInfo.getState(), 2)) {//部门调动审核
            if (stateDto.getState() == 0 && userInfo.getType() == 2) {//审核通过
                auditUserDeptApply(userInfo, true);
            } else {
                auditUserDeptApply(userInfo, false);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param userID
     * @param isStop 修改状态（0启用，1停用)
     * @return
     */
    public String enableOrDisableUser(Long userID, Integer isStop) {
        if (!Objects.equal(isStop, 0) && !Objects.equal(isStop, 1)) {
            throw new ServiceException("参数错误");
        }
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (userInfo == null) {
            throw new ServiceException("未找到用户");
        }
        userInfo.setIsStop(isStop);
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
        return "success";
    }

    //停用启用用户【0启用/审核通过，1停用】
    public synchronized Object updateIsStop(StateDto stateDto) {
        if (stateDto.getState() < 0 || stateDto.getState() > 2) {
            throw new ServiceException("传递的参数错误", RestConst.ErrorCode.FORM_FAIL);
        }
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(stateDto.getuID());
        if (auditDept(userInfo, stateDto)) {
            return "success";
        }

        if (userInfo.getType() == 1) {
            if (userInfo.getAccount().equals("admin")) {  //如果是总行admin则不能操作
                throw new ServiceException("该账号不能操作", RestConst.ErrorCode.FORM_FAIL);
            }
            Organizational organizational = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            if (organizational.getLevel() != 1) { //如果是下级银行管理账户，不能操作
                throw new ServiceException("该账号不能操作", RestConst.ErrorCode.FORM_FAIL);
            }
        }
        //停用则删除登录信息
        if (stateDto.getState() == 1) {
            userLoginMapper.deleteByUserID(stateDto.getuID());
        }
        //如果是销售经理通过审核，则生成对应的6位数推荐码
        if (stateDto.getState() == 0 && userInfo.getType() == 2 && userInfo.getIsStop() == 2) {
            setManagerPoint(userInfo);  //审核通过送金豆
            userInfo.setRecommendNO(getRecommendNO(1));
            userInfoMapper.updateByPrimaryKeySelective(userInfo);

            //初始化记录
            userTransferService.saveUserTransferRecord(userInfo, null, true);
            //审核通过则发送短信
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", userInfo.getMobile()); //下单人手机
            jsonObject.put("type", SmsTempEnum.USER_CHECK.getCode());
            jsonObject.put("param", new String[]{});

            DataResult result = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);

            if (result.getIsSuccess() != 1) {
                logger.error("调用短信服务失败:" + result.getErrorDesc());
            }
            if (logger.isDebugEnabled()) {
                logger.info("发送order通知短信ok.... " + userInfo.getMobile());
            }
        }

        //从停用状态到启用则添加登录信息
        if (userInfo.getIsStop() == 1) {
            if (stateDto.getState() == 0) {
                UserLogin userLogin = new UserLogin();
                userLogin.setUserID(userInfo.getUserID());
                userLogin.setPassWord(userInfo.getPassWord());
                userLogin.setCompanyID(SystemContext.getCompanyID());
                if (userInfo.getAccount().equals(userInfo.getMobile())) {
                    userLogin.setId(IdGen.get().nextId());
                    userLogin.setLoginName(userInfo.getAccount());
                    userLoginMapper.insertSelective(userLogin);
                } else {
                    if (userInfo.getAccount() != null) {
                        userLogin.setId(IdGen.get().nextId());
                        userLogin.setLoginName(userInfo.getAccount());
                        userLoginMapper.insertSelective(userLogin);
                    }
                    if (userInfo.getMobile() != null) {
                        userLogin.setId(IdGen.get().nextId());
                        userLogin.setLoginName(userInfo.getMobile());
                        userLoginMapper.insertSelective(userLogin);
                    }
                }
                userTransferService.saveUserTransferRecord(userInfo, null, false);
            }
        }
        userInfoMapper.updateIsStop(stateDto);


        return "success";
    }

    //按条件查询用户列表
    public PageInfo selectUiList(int pageNum, int pageSize, UserSelectDto selectDto) {
        selectDto.setCompanyID(SystemContext.getCompanyID());
        if (selectDto.getPaterIDList().size() > 0) {
            List<Long> paterIDList = userInfoMapper.selectConsultantIDByManagerID(selectDto.getPaterIDList().get(0));
            if (paterIDList == null) {
                paterIDList = new ArrayList<>();
            }
            paterIDList.add(selectDto.getPaterIDList().get(0));
            selectDto.setPaterIDList(paterIDList);
        }
        if (selectDto.getoIDList().size() > 0) {
            Organizational organizational = organizationalMapper.selectByPrimaryKey(selectDto.getoIDList().get(0));
            Map<String, Object> params = new HashMap<>();
            params.put("companyID", SystemContext.getCompanyID());
            switch (organizational.getLevel()) {
                case 1:
                    selectDto.setoIDList(null);
                    break;
                case 2:
                    params.put("branchID", selectDto.getoIDList().get(0));
                    List<Long> subOIDList = organizationalMapper.selectSubOIDList(params);
                    if (subOIDList == null) {
                        subOIDList = new ArrayList<>();
                    }
                    subOIDList.add(selectDto.getoIDList().get(0));
                    selectDto.setoIDList(subOIDList);
                    break;
                case 3:
                    params.put("twoLevelBranchID", selectDto.getoIDList().get(0));
                    List<Long> subSubOIDList = organizationalMapper.selectSubOIDList(params);
                    if (subSubOIDList == null) {
                        subSubOIDList = new ArrayList<>();
                    }
                    subSubOIDList.add(selectDto.getoIDList().get(0));
                    selectDto.setoIDList(subSubOIDList);
                    break;
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> uiList = userInfoMapper.selectByCondition(selectDto);
        if (uiList.size() == 0) {
            return null;
        }
        for (UserInfoVo userInfo : uiList) {
            userInfo.setPassWord(null);
            Organizational oz = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            if (oz == null) {
                userInfo.setOrganizationalName("该用户未查到组织");
            } else {
                switch (oz.getLevel()) {
                    case 1:
                        userInfo.setOrganizationalName("总部");
                        if (userInfo.getType() == 1) {
                            userInfo.setRoleName(getRoleName(userInfo.getUserID()));  //获取角色名字信息
                        }
                        break;
                    case 2:
                        userInfo.setOrganizationalName("总部/" + oz.getOrganizationalName());
                        break;
                    case 3:
                        Organizational ozt = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                        userInfo.setOrganizationalName("总部/" + ozt.getOrganizationalName() + "/" + oz.getOrganizationalName());
                        break;
                    case 4:
                        Organizational oztb = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                        Organizational oztt = organizationalMapper.selectByPrimaryKey(oz.getTwoLevelBranchID());
                        userInfo.setOrganizationalName("总部/" + oztb.getOrganizationalName() + "/" + oztt.getOrganizationalName() + "/" + oz.getOrganizationalName());
                        break;
                }
            }

            if (userInfo.getType() == 3 || userInfo.getType() == 4) {
                UserAddress userAddress = userAddressMapper.selectDefaultAddressByUserID(userInfo.getUserID());
                if (userAddress == null) {
                    userInfo.setAddressInfo("该会员尚未填写地址");
                } else {
                    userInfo.setAddressInfo(userAddress.getAddress());
                }

                if (userInfo.getPaterID() == 0) {
                    Organizational oz2 = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
                    userInfo.setPaterName(oz2.getOrganizationalName() + "直属会员");
                } else {
                    UserInfo paterInfo = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                    if (paterInfo == null) {
                        userInfo.setPaterName("未查到关联人信息");
                    } else {
                        userInfo.setPaterType(paterInfo.getType());
                        userInfo.setPaterName(paterInfo.getName());
                    }
                }
            }
        }
        PageInfo<UserInfoVo> page = new PageInfo(uiList);
        return page;
    }

    //纯粹按传入条件查询用户列表
    public PageInfo selectUiListByConditon(int pageNum, int pageSize, UserSelectDto selectDto) {
        PageHelper.startPage(pageNum, pageSize);

        selectDto.setEmployAuditFlag(1);
        if (Objects.equal(selectDto.getIsStop(), "2")) {//待审核
            List<Long> oIDList = selectDto.getoIDList();
            if (CollectionUtils.isNotEmpty(oIDList)) {
                Long oID = oIDList.get(0);
                //TODO 总部或超级管理员可以查看
                TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(SystemContext.getCompanyID());
                Long deptID = topDeptEnum.getDeptID();
                if (Objects.equal(deptID, oID)) {//总部
                    selectDto.setEmployAuditFlag(0);
                }
            }
        }
        selectDto.setCompanyID(SystemContext.getCompanyID());
        List<UserInfoVo> uiList = userInfoMapper.selectByCondition2(selectDto);
        for (UserInfoVo userInfo : uiList) {
            Organizational oz = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            switch (oz.getLevel()) {
                case 1:
                    userInfo.setOrganizationalName("总部");
                    if (userInfo.getType() == 1) {
                        userInfo.setRoleName(getRoleName(userInfo.getUserID()));  //获取角色名字信息
                    }
                    break;
                case 2:
                    userInfo.setOrganizationalName("总部/" + oz.getOrganizationalName());
                    break;
                case 3:
                    Organizational ozt = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                    userInfo.setOrganizationalName("总部/" + ozt.getOrganizationalName() + "/" + oz.getOrganizationalName());
                    break;
                case 4:
                    Organizational oztb = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                    Organizational oztt = organizationalMapper.selectByPrimaryKey(oz.getTwoLevelBranchID());
                    userInfo.setOrganizationalName("总部/" + oztb.getOrganizationalName() + "/" + oztt.getOrganizationalName() + "/" + oz.getOrganizationalName());
                    break;
            }

            if (userInfo.getType() == 3 || userInfo.getType() == 4) {
                UserAddress userAddress = userAddressMapper.selectDefaultAddressByUserID(userInfo.getUserID());
                if (userAddress == null) {
                    userInfo.setAddressInfo("该会员尚未填写地址");
                } else {
                    userInfo.setAddressInfo(userAddress.getAddress());
                }

                if (userInfo.getPaterID() == 0) {
                    Organizational ozz = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
                    userInfo.setPaterName(ozz.getOrganizationalName() + "直属会员");
                } else {
                    UserInfo paterInfo = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                    if (paterInfo == null) {
                        userInfo.setPaterName("未查到关联人信息");
                    } else {
                        userInfo.setPaterType(paterInfo.getType());
                        userInfo.setPaterName(paterInfo.getName());
                    }
                }
            }
        }

        PageInfo<UserInfoVo> page = new PageInfo(uiList);
        return page;
    }

    /**
     * 激活用户
     *
     * @param userInfo
     */
    public void activeUser(UserInfo userInfo) {
        //激活用户
        if (Objects.equal(userInfo.getState(), 0)) {
            UserInfo _userinfo = new UserInfo();
            _userinfo.setUserID(userInfo.getUserID());
            _userinfo.setState(1);
            updateByPrimaryKeySelective(_userinfo);
        }
    }

    //查询总行的管理账号列表
    public PageInfo selectAdminUserList(int pageNum, int pageSize, String account) {
        UserSelectDto selectDto = new UserSelectDto();
        List<Integer> typeList = new ArrayList<>();
        typeList.add(1);
        Organizational organizational = organizationalMapper.selectHeadCCB(SystemContext.getCompanyID());
        List<Long> oIDList = new ArrayList<>();
        oIDList.add(organizational.getoID());
        selectDto.setTypeList(typeList);
        selectDto.setoIDList(oIDList);
        selectDto.setAccount(account);
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVo> uiList = userInfoMapper.selectByCondition(selectDto);
        for (UserInfoVo userInfoVo : uiList) {
            userInfoVo.setRoleName(getRoleName(userInfoVo.getUserID()));
        }
        PageInfo<UserInfoVo> page = new PageInfo(uiList);
        return page;
    }

    //id查询用户信息
    public UserInfo selectByUserID(Long userID) {
        UserInfo ui = userInfoMapper.selectByPrimaryKey(userID);
        if (ui == null) {
            return null;
        } else {
            ui.setPassWord(null);
        }
        return ui;
    }

    public Map<String, Object> selectWithDeptByUserID(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (userInfo == null) {
            throw new ServiceException("未获取到用户");
        }
        if (!Objects.equal(userInfo.getIsAdmin(), 1)) {
            return null;
        }
        List<Organizational> organizationals = organizationalMapper.selectByAdminID(userID);
        if (CollectionUtils.isEmpty(organizationals)) {
            return null;
        }
        boolean isSecondDeptAdmin = false;
        boolean isThirdDeptAdmin = false;
        boolean isFourthDeptAdmin = false;
        //判断是否是省代管理者或加盟店管理者
        for (Organizational organizational : organizationals) {
            //1总行 2分行 3二级分行 4支行
            if (Objects.equal(organizational.getLevel(), 2)) {
                isSecondDeptAdmin = true;
                break;
            }
            if (Objects.equal(organizational.getLevel(), 3)) {
                isThirdDeptAdmin = true;
                break;
            } else if (Objects.equal(organizational.getLevel(), 4)) {
                isFourthDeptAdmin = true;
                break;
            }
        }
        Map<String, Object> map = JsonUtil.toMap(userInfo);
        map.put("isSecondDeptAdmin", isSecondDeptAdmin);
        map.put("isThirdDeptAdmin", isThirdDeptAdmin);
        map.put("isFourthDeptAdmin", isFourthDeptAdmin);
        return map;
    }


    //id查询用户信息
    public Object selectLevelByUserID(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (userInfo == null) {
            return null;
        }
        JSONObject jsonObject = JSONObject.fromObject(userInfo);
        Organizational organizational = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
       /* jsonObject.put("type",userInfo.getType());
        jsonObject.put("vipLevel",userInfo.getVipLevel());*/
        jsonObject.put("level", organizational.getLevel());
        return jsonObject;
    }

    /**
     * userID查询会员详情信息,包括交易额
     *
     * @param userID
     * @param uType  1统计当前身份交易额 2销售顾问仅统计自身交易额
     * @return
     * @throws Exception
     */
    public Object selectUserByUserID(Long userID, int uType) throws Exception {
        UserInfo ui = userInfoMapper.selectByPrimaryKey(userID);
        Integer isShopBoss = 0;
        if (ui == null) {
            throw new ServiceException("未查到用户信息", RestConst.ErrorCode.DATABASE_ERROR);
        }
        ui.setPassWord(null);
        int type = ui.getType();
        UserInfoMoreDto moreDto = new UserInfoMoreDto();
        UserLogin userLogin = userLoginMapper.selectLoginName(ui.getAccount(), ui.getCompanyID());
        BeanUtils.copyProperties(moreDto, ui);
        if (userLogin == null) {
            moreDto.setRecentTime("未查到用户登录记录");
        } else {
            moreDto.setRecentTime(userLogin.getLoginTime() == null ? null : userLogin.getLoginTime().toString());
        }
        Long oID = 0l;
        int level = 0;
        if (type == 1 || type == 2) {
            Organizational organizational = organizationalMapper.selectByPrimaryKey(ui.getOrganizationalID());
            moreDto.setOrganizationalName(organizational.getOrganizationalName());
            oID = organizational.getoID();
            level = organizational.getLevel();
            if (organizational.getAdminID() != null && organizational.getAdminID() != 0L && Objects.equal(organizational.getAdminID(), userID)) {
                isShopBoss = 1;
            }
        }
        if (type == 3) { //销售顾问
            switch (uType) {
                case 1:
                    type = 3;  //统计销售顾问及其下属交易额
                    break;
                case 2:
                    type = 4;  //作为会员仅统计销售顾问本身交易额
                    break;
            }
        }
        String url = ProConstants.getUserTransaction + userID + "/" + type + "/" + level + "/" + oID;
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(url, restTemplate);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用bank服务失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<String, Object> param = (Map<String, Object>) jsonObject.get("data");
        moreDto.setOrderQty(param.get("orderQty").toString());
        moreDto.setGoodsQty(param.get("goodsQty").toString());
        moreDto.setTransactionTotal(param.get("transactionTotal").toString());

        moreDto.setIsShopBoss(isShopBoss);

        return moreDto;
    }

    //按账户查询用户
    public UserInfo selectByAccount(String acccount, Long companyID) {
        return userInfoMapper.selectByAccount(acccount, companyID);
    }

    //查询推荐人手机号
    public UserInfo selectRecommenderPhone(String phone, Long companyID) {
        return userInfoMapper.selectRecommenderPhone(phone, companyID);
    }

    //查询推荐人推荐码
    public UserInfo selectByRecommendNO(int code) {
        return userInfoMapper.selectByRecommendNO(code, SystemContext.getCompanyID());
    }

    //查询用户的角色
    public List<UserRole> selectUserRoleByUserID(Long userID) {
        return userRoleMapper.selectByUserID(userID);
    }

    //查询用户所拥有的权限code
    public List<String> getFunCodeByUserID(Long userID) {
        List<String> funCodeList = new ArrayList<>();
        List<UserRole> urList = userRoleMapper.selectByUserID(userID);
        if (urList.size() > 0) {
            for (UserRole ur : urList) {
                RoleAndFuncDto rfDto = roleService.selectRoleAndFuncByID(ur.getRoleID());
                if (rfDto.getFuncList().size() > 0) {  //该角色所拥有的权限List
                    for (Permissions permissions : rfDto.getFuncList()) {
                        if (!funCodeList.contains(permissions.getCode())) {
                            funCodeList.add(permissions.getCode());
                        }
                    }
                }
            }
        }
        return funCodeList;
    }

    //更新用户角色
    public List<UserRole> updateUserRole(Long userID, List<UserRole> urList) {
        userRoleMapper.deleteByUserID(userID);
        for (UserRole ur : urList) {
            ur.setID(IdGen.get().nextId());
        }
        userRoleMapper.batchInsert(urList);
        return userRoleMapper.selectByUserID(userID);
    }

    //地址新增
    public Long addAddress(UserAddress userAddress) {
        List<UserAddress> uaList = userAddressMapper.selectByUserID(userAddress.getUserID());
        if (uaList.size() > 0) {
            if (userAddress.getIsDefault() == 1) {  //如果地址不止一个，并且新增地址为默认
                userAddressMapper.updateNoDefaultByUserID(userAddress.getUserID());
            } else {
                userAddress.setIsDefault(0);
            }
        } else {
            userAddress.setIsDefault(1);//如果只有这一个地址则设置为默认
        }
        userAddress.setId(IdGen.get().nextId());
        userAddress.setAddTime(CommonUtils.getCurTimestamp());
        userAddressMapper.insertSelective(userAddress);
        return userAddress.getId();
    }

    //修改地址
    public Object updateAddress(UserAddress userAddress) {
        UserAddress ua = userAddressMapper.selectByPrimaryKey(userAddress.getId());
        userAddress.setIsDefault(ua.getIsDefault());  //是否默认不可改；
        userAddressMapper.updateByPrimaryKeySelective(userAddress);
        return userAddressMapper.selectByPrimaryKey(userAddress.getId());
    }

    //删除地址
    public Object deleteAddress(Long id) {
        UserAddress ua = userAddressMapper.selectByPrimaryKey(id);
        if (ua.getIsDefault() == 1) { //如果删除的是默认地址
            userAddressMapper.setDeleteFlag(id);
            List<UserAddress> uaList = userAddressMapper.selectByUserID(ua.getUserID());
            if (uaList.size() > 0) { //并且还有地址存在，则选择最新地址为默认
                Long aID = uaList.get(0).getId();
                userAddressMapper.updateIsDefault(aID);
            }
        } else {
            userAddressMapper.setDeleteFlag(id);
        }
        return userAddressMapper.selectByUserID(ua.getUserID());
    }

    //设置默认地址
    public Object updateAdressDefault(Long id) {
        UserAddress ua = userAddressMapper.selectByPrimaryKey(id);
        userAddressMapper.updateNoDefaultByUserID(ua.getUserID());
        userAddressMapper.updateIsDefault(ua.getId());
        return userAddressMapper.selectByUserID(ua.getUserID());
    }

    //按id查询地址
    public UserAddress selectAddressByID(Long id) {
        return userAddressMapper.selectByPrimaryKey(id);
    }

    //按userID查询地址
    public List<UserAddress> selectAddressByUserID(Long userID) {
        return userAddressMapper.selectByUserID(userID);
    }

    //判断会员是否总行下属
    public Object judgeHCCBByUserID(Long userID) {
        UserInfo uiVip = userInfoMapper.selectByPrimaryKey(userID);//查询会员用户信息
        Organizational oz = organizationalMapper.selectByPrimaryKey(uiVip.getOrganizationalID());
        if (oz == null) {
            throw new ServiceException("未查到该会员的组织信息", RestConst.ErrorCode.DATABASE_ERROR);
        }
        Map<String, Object> resultMap = new HashMap<>();
        Integer manageerPhone = 0;
        if (uiVip.getPaterID() == 0) {
            resultMap.put("manageerPhone", manageerPhone);
            resultMap.put("bank", oz.getOrganizationalName());
            return resultMap;
        }

        UserInfo uiPater = userInfoMapper.selectByPrimaryKey(uiVip.getPaterID());//查询会员上级用户信息
        resultMap.put("bank", oz.getOrganizationalName());
        if (uiPater.getType() == 3) { //如果会员上级用户是销售顾问
            UserInfo uiManager = userInfoMapper.selectByPrimaryKey(uiPater.getPaterID());
            if (uiManager == null) {
                throw new ServiceException("销售顾问未查到员工，请联系管理员", RestConst.ErrorCode.DATABASE_ERROR);
            }
            resultMap.put("manageerPhone", uiManager.getRecommendNO());
        } else if (uiPater.getType() == 2) {
            resultMap.put("manageerPhone", uiPater.getRecommendNO());
        }
        return resultMap;
    }


    //会员提交申请成为销售顾问
    public Object addApply(UserApply userApply) {
        UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(userApply.getUserId());
        if (userInfo1.getType() != 4) {
            throw new ServiceException("只有会员才能申请成为销售顾问", RestConst.ErrorCode.FORM_FAIL);
        }
        if (userApply.getMobile() == null || userApply.getMobile().equals("")) {
            throw new ServiceException("推荐人手机号不能为空", RestConst.ErrorCode.FORM_FAIL);
        }
        UserInfo ui = userInfoMapper.selectByRecommendNO(Integer.parseInt(userApply.getMobile()), SystemContext.getCompanyID());
        if (ui == null) {
            throw new ServiceException("未查到推荐码对应的员工", RestConst.ErrorCode.DATABASE_ERROR);
        } else if ((ui.getType() != 2)) {
            throw new ServiceException("所传推荐码不是销售经理", RestConst.ErrorCode.DATABASE_ERROR);
        }

        UserApply userApply1 = userApplyMapper.selectByUserID(userApply.getUserId());
        if (userApply1 != null) {
            if (userApply1.getState() == 1 || userApply1.getState() == 2) {
                throw new ServiceException("已经提交过审核申请", RestConst.ErrorCode.FORM_FAIL);
            }
            if (userApply1.getState() == 0) {
                userApplyMapper.deleteByUserID(userApply.getUserId());
            }
        }
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userApply.getUserId());
        userApply.setId(IdGen.get().nextId());
        userApply.setAccount(userInfo.getAccount());
        userApply.setState(2);
        userApply.setAddTime(CommonUtils.getCurTimestamp());
        userApply.setCompanyID(SystemContext.getCompanyID());
        userApplyMapper.insertSelective(userApply);
        return userApply.getId();
    }

    //用户查询申请审核信息
    public UserApplyMoreVo selectApplyState(Long userID) throws Exception {
        UserApply userApply = userApplyMapper.selectByUserID(userID);
        if (userApply == null) {
            UserApplyMoreVo userApply1 = new UserApplyMoreVo();
            userApply1.setState(3);
            userApply1.setUserId(userID);
            Organizational oz = organizationalMapper.selectByPrimaryKey(userInfoMapper.selectByPrimaryKey(userID).getOrganizationalID());
            userApply1.setOrganizationalName(oz.getOrganizationalName());
            return userApply1;
        } else {
            UserApplyMoreVo moreVo = new UserApplyMoreVo();
            BeanUtils.copyProperties(moreVo, userApply);
            Organizational oz = organizationalMapper.selectByPrimaryKey(userInfoMapper.selectByPrimaryKey(userID).getOrganizationalID());
            moreVo.setOrganizationalName(oz.getOrganizationalName());
            return moreVo;
        }
    }

    /**
     * TODO 审核员部门调动申请
     *
     * @param userInfo
     * @return
     */
    public Boolean auditUserDeptApply(UserInfo userInfo, boolean pass) {
        //更新员工状态和审核时间
        //UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (pass) {
            List<Organizational> organizationals = organizationalMapper.selectByAdminID(userInfo.getUserID());
            if (Objects.equal(userInfo.getIsAdmin(), 1)) {
                if (CollectionUtils.isNotEmpty(organizationals)) {
                    Organizational organizational = organizationals.get(0);
                    organizationalMapper.clearAdmin(organizational.getoID());
                }
            }

            Long newOid = userInfo.getLastOrganizationalID();
            Long oldID = userInfo.getOrganizationalID();
            userInfo.setLastOrganizationalID(oldID);
            userInfo.setOrganizationalID(newOid);
            userInfo.setState(3);
            userInfo.setIsStop(0);
            userInfo.setIsAdmin(2);
            userInfo.setLastTransferTime(System.currentTimeMillis());
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
            userTransferService.parseEmployee(userInfo.getUserID());
            // 员工部门调度记录
            userTransferService.checkUserTransferRecord(userInfo, true);

            updateEmployOffline(userInfo);
        } else {
            userInfo.setState(1);
            userInfo.setIsStop(0);
            userTransferService.checkUserTransferRecord(userInfo, false);
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        return true;
    }

    public void updateEmployOffline(UserInfo employ) {
        List<UserInfo> list = userInfoMapper.selectByPaterID(employ.getUserID());
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (UserInfo userInfo : list) {
            if (Objects.equal(userInfo.getType(), 3)) {//销售顾问
                userInfo.setOrganizationalID(employ.getOrganizationalID());
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
                updateEmployOffline(userInfo);//下线会员
            } else {
                userInfo.setOrganizationalID(employ.getOrganizationalID());
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
        }
    }

    public String batchUpdateRecommender(RecommenderDto dto) {
        if (CollectionUtils.isEmpty(dto.getUserIds())) {
            throw new ServiceException("未选择用户信息");
        }
        UserInfo employee;
        if (dto.getEmployeeID() == null || dto.getEmployeeID() == 0) {
            employee = new UserInfo();
            employee.setOrganizationalID(TopDeptEnum.valuekOf(SystemContext.getCompanyID()).getDeptID());
            employee.setUserID(0L);
        } else {
            employee = userInfoMapper.selectByPrimaryKey(dto.getEmployeeID());
            if (employee == null) {
                throw new ServiceException("未获取到员工信息");
            }
        }

        List<Long> userIds = dto.getUserIds();
        for (Long userID : userIds) {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
            if (userInfo == null) {
                continue;
                //throw new ServiceException("未获取到用户信息"+userID);
            }
            userInfo.setPaterID(employee.getUserID());
            userInfo.setOrganizationalID(employee.getOrganizationalID());
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        return "success";
    }

    //销售顾问审核(0失败，1成功)
    public String updateApplyState(UserApply userApply) {
        UserApply uap = userApplyMapper.selectByPrimaryKey(userApply.getId());
        if (uap.getState() == 1) {
            throw new ServiceException("已经成为销售顾问", RestConst.ErrorCode.DATABASE_ERROR);
        }
        if (userApply.getState() == 1) {
            UserInfo ui = userInfoMapper.selectByRecommendNO(Integer.parseInt(userApply.getMobile()), SystemContext.getCompanyID());//获取上级的信息
            if (ui == null) {
                throw new ServiceException("未查到推荐码对应的员工", RestConst.ErrorCode.DATABASE_ERROR);
            } else if ((ui.getType() != 2)) {
                throw new ServiceException("所传推荐码不是销售经理", RestConst.ErrorCode.DATABASE_ERROR);
            }

            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userApply.getUserId());
            if (userInfo.getType() == 3) {
                throw new ServiceException("已经成为销售顾问", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (userInfo.getAddTime() < getTimesamp()) {  //成为销售顾问不是成为会员同一天
                countMapper.updateMemberCountQty(0l);  //总会员减1
                Organizational oz = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
                if (oz.getLevel() == 1) {
                    countMapper.updateMemberCountQty(1l);
                } else {
                    UserCountDto userCountDto = new UserCountDto();
                    switch (oz.getLevel()) {
                        case 2:
                            userCountDto.setBranchID(oz.getoID());
                            userCountDto.setTwoLevelBranchID(0l);
                            userCountDto.setSubbranchID(0l);
                            userCountDto.setSalesManagerID(0l);
                            break;
                        case 3:
                            userCountDto.setTwoLevelBranchID(oz.getoID());
                            userCountDto.setSubbranchID(0l);
                            userCountDto.setSalesManagerID(0l);
                            break;
                        case 4:
                            userCountDto.setSubbranchID(oz.getoID());
                            userCountDto.setSalesManagerID(0l);
                            break;
                        default:
                            throw new ServiceException("异常错误", RestConst.ErrorCode.UNKNOWN);
                    }
                    Long id = countMapper.selectIDByConditon(userCountDto);
                    countMapper.updateMemberCountQty(id);
                }
                //如果属于某个销售经理，则该销售经理下的数量也减1
                if (userInfo.getPaterID() != 0 && userInfo.getPaterID() != null) {
                    Long managerID;
                    UserInfo paterInfo = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                    managerID = userInfo.getPaterID();
                    if (paterInfo.getType() == 3) { //如果上级是销售顾问
                        managerID = paterInfo.getPaterID();
                    }
                    UserCountDto userCountDto = new UserCountDto();
                    userCountDto.setSalesManagerID(managerID);
                    Long id = countMapper.selectIDByConditon(userCountDto);
                    countMapper.updateMemberCountQty(id);
                }
            }

            UserApply ua = userApplyMapper.selectByPrimaryKey(userApply.getId());
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userID", ua.getUserId());
            param.put("paterID", ui.getUserID());
            param.put("organizationalID", ui.getOrganizationalID()); //和上级一样的组织
            param.put("name", ua.getName());  //申请时填的姓名
            param.put("updateTime", CommonUtils.getCurTimestamp());
            param.put("recommendNO", getRecommendNO(2));  //八位数推荐码
            userInfoMapper.updateToConsultant(param);
        }
        userApplyMapper.updateByPrimaryKeySelective(userApply);
        return "success";
    }

    //按条件查询申请销售顾问列表
    public PageInfo uaList(int pageNum, int pageSize, ApplyDto applyDto) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        List<UserApplyMoreVo> moreVoList = new ArrayList<>();
        applyDto.setCompanyID(SystemContext.getCompanyID());
        List<UserApply> uaList = userApplyMapper.selectByConditon(applyDto);
        for (UserApply userApply : uaList) {
            UserApplyMoreVo moreVo = new UserApplyMoreVo();
            BeanUtils.copyProperties(moreVo, userApply);
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userApply.getUserId());
            moreVo.setApplyMobile(userInfo.getMobile());
            moreVoList.add(moreVo);
        }
        PageInfo<UserApplyMoreVo> page = new PageInfo(moreVoList);
        return page;
    }

    //用户提交意见内容
    public String addFeedback(Feedback feedback) {
        feedback.setId(IdGen.get().nextId());
        feedback.setAddTime(CommonUtils.getCurTimestamp());
        feedback.setCompanyID(SystemContext.getCompanyID());
        feedbackMapper.insertSelective(feedback);
        return "success";
    }

    //TODO 获取用户下订单需要得到的用户及其组织信息
    public UserInfoForOrderDto getUserInfoForOrder(Long userID) {
        UserInfoForOrderDto orderInfo = new UserInfoForOrderDto();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        orderInfo.setUserName(userInfo.getName());
        orderInfo.setMobile(userInfo.getMobile());
        orderInfo.setCompanyID(userInfo.getOrganizationalID());
        orderInfo.setType(userInfo.getType());
        //会员级别
        orderInfo.setVipLevel(userInfo.getVipLevel().longValue());
        if (userInfo.getType() == 4 || userInfo.getType() == 6) {
            if (userInfo.getPaterID() != 0 && userInfo.getPaterID() != null) {
                UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                if (userInfo1.getType() == 3) { //上级是销售顾问
                    orderInfo.setSalesID(userInfo.getPaterID());
                    orderInfo.setSalesManagerID(userInfo1.getPaterID());
                } else if (userInfo1.getType() == 2) { //上级是销售经理
                    orderInfo.setSalesManagerID(userInfo.getPaterID());
                }
            }
        } else if (userInfo.getType() == 3) {
            orderInfo.setSalesManagerID(userInfo.getPaterID());
            orderInfo.setSalesID(userID);
        } else if (userInfo.getType() == 2) {
            orderInfo.setSalesManagerID(userID);
        }

        if (orderInfo.getSalesManagerID() == null) {
            orderInfo.setSalesManagerID(0L);
        }

        Long mDeptID = 0L;
        Organizational organizational = null;
        if (Objects.equal(userInfo.getType(), 1)) {
            mDeptID = userInfo.getOrganizationalID();
            organizational = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
        } else {
            if (orderInfo.getSalesManagerID() == 0) {
                orderInfo.setBranchID(0L);
                orderInfo.setTwoLevelBranchID(0L);
                orderInfo.setSubbranchID(0L);
                return orderInfo;
            } else {
                UserInfo employ = userInfoMapper.selectByPrimaryKey(orderInfo.getSalesManagerID());
                //TODO 判断是否是当天调度
                if (!Objects.equal(employ.getState(), 2)) {//调度已经生效
                    if (employ.getLastTransferTime() != null && DateUtils.isSameDay(new Date(employ.getLastTransferTime()), new Date(System.currentTimeMillis()))) {
                        mDeptID = employ.getLastOrganizationalID();
                        organizational = organizationalMapper.selectByPrimaryKey(employ.getLastOrganizationalID());
                    } else {
                        mDeptID = employ.getOrganizationalID();
                        organizational = organizationalMapper.selectByPrimaryKey(employ.getOrganizationalID());
                    }
                } else {
                    mDeptID = employ.getOrganizationalID();
                    organizational = organizationalMapper.selectByPrimaryKey(employ.getOrganizationalID());
                }
            }
        }
        if (organizational == null) {
            //未找到组织架构
            Organizational preOrganizational = getPreDept(organizationalMapper.selectByOID(mDeptID));
            if (preOrganizational == null) {
                orderInfo.setBranchID(0L);
                orderInfo.setTwoLevelBranchID(0L);
                orderInfo.setSubbranchID(0L);
                return orderInfo;
            }
            organizational = preOrganizational;
        }
        orderInfo.setoLevel(organizational.getLevel());
        switch (organizational.getLevel()) {
            case 2:
                orderInfo.setBranchID(organizational.getoID());
                break;
            case 3:
                orderInfo.setBranchID(organizational.getBranchID());
                orderInfo.setTwoLevelBranchID(organizational.getoID());
                break;
            case 4:
                orderInfo.setBranchID(organizational.getBranchID());
                orderInfo.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                orderInfo.setSubbranchID(organizational.getoID());
                break;
        }

        return orderInfo;
    }

    private Organizational getPreDept(Organizational organizational) {
        if (organizational == null) {
            return null;
        }
        Long preDeptID = organizationalService.getPreDeptID(organizational);
        Organizational preOrganizational = organizationalMapper.selectByOID(preDeptID);
        //没找到部门信息
        if (preOrganizational == null) {
            return null;
        }
        if (Objects.equal(preOrganizational.getState(), 1)) {//已删除
            return getPreDept(preOrganizational);
        }
        return preOrganizational;
    }

    //获取用户用于生产统计表的组织信息
    public UserCountDto getOInfoForCount(Long userID) {
        UserCountDto userCountDto = new UserCountDto();
        UserInfo ui = userInfoMapper.selectByPrimaryKey(userID);
        Organizational organizational = organizationalMapper.selectByPrimaryKey(ui.getOrganizationalID());
        switch (organizational.getLevel()) {
            case 1:
                userCountDto.setBranchID(0l);
                break;
            case 2:
                userCountDto.setBranchID(organizational.getoID());
                break;
            case 3:
                if (organizational.getBranchID() == null) {
                    throw new ServiceException("请选择上级分行", RestConst.ErrorCode.FORM_FAIL);
                }
                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getoID());
                break;
            case 4:
                if (organizational.getBranchID() == null && organizational.getTwoLevelBranchID() == null) {
                    throw new ServiceException("请选择上级二级分行和分行", RestConst.ErrorCode.FORM_FAIL);
                }
                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                userCountDto.setSubbranchID(organizational.getoID());
                break;
        }
        if (ui.getType() == 3) {
            userCountDto.setSalesManagerID(ui.getPaterID());
        }
        return userCountDto;
    }

    //查询销售经理下需要审核申请销售顾问的数量
    public int selectUserApplyIsAuditQty(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        return userApplyMapper.selectUserApplyIsAuditQty(userInfo.getRecommendNO().toString(), userInfo.getCompanyID());
    }

    //查询用户的溯源信息【销售顾问、销售经理、组织名字】
    public Object selectTraceability(Long userID, Long salesManagerID, Long deptID) {
        if (salesManagerID == null) {
            return selectTraceability(userID);//老版本
        } else {
            return selectTraceabilityForNew(userID, salesManagerID, deptID);
        }
    }

    @Deprecated
    public Object selectTraceability(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        OrderTraceabilityVo traceabilityVo = new OrderTraceabilityVo();
        if (userInfo.getType() == 4) {
            if (userInfo.getPaterID() != 0 && userInfo.getPaterID() != null) {
                UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                if (userInfo1.getType() == 3) { //上级是销售顾问
                    traceabilityVo.setSalesName(userInfo1.getName());
                    UserInfo userInfo2 = userInfoMapper.selectByPrimaryKey(userInfo1.getPaterID());
                    traceabilityVo.setManagerName(userInfo2.getName());
                } else if (userInfo1.getType() == 2) { //上级是销售经理
                    traceabilityVo.setManagerName(userInfo1.getName());
                }
            }
        } else if (userInfo.getType() == 3) {  //销售顾问上级就是销售经理
            UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
            traceabilityVo.setManagerName(userInfo1.getName());
        }

        if (userInfo.getShopID() != null) {
            CompanyInfo shopInfo = companyInfoMapper.selectByPrimaryKey(userInfo.getShopID());
            traceabilityVo.setShopName(shopInfo.getCompanyName());
        }

        Organizational oz = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
        String opathName = retOpathtName(oz);
        if (null != opathName && !"".equals(opathName)) {
            traceabilityVo.setOpathName(opathName + "/" + oz.getOrganizationalName());
        } else {
            traceabilityVo.setOpathName(oz.getOrganizationalName());
        }
        traceabilityVo.setOrganizationalName(oz.getOrganizationalName());
        return traceabilityVo;
    }

    public Object selectTraceabilityForNew(Long userID, Long salesManagerID, Long deptID) {
        //UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        OrderTraceabilityVo traceabilityVo = new OrderTraceabilityVo();

        //获取店铺信息
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (userInfo.getShopID() != null) {
            CompanyInfo shopInfo = companyInfoMapper.selectByPrimaryKey(userInfo.getShopID());
            traceabilityVo.setShopName(shopInfo.getCompanyName());
        }


        if (salesManagerID == null || salesManagerID == 0) {//未找到销售经理
            traceabilityVo.setManagerName("");
        } else {
            UserInfo employee = userInfoMapper.selectByPrimaryKey(salesManagerID);
            if (employee == null) {
                traceabilityVo.setManagerName("");
            } else {
                traceabilityVo.setManagerName(employee.getName());
            }
        }
        if (Objects.equal(deptID, 0L)) {
            traceabilityVo.setOpathName("总部");
            traceabilityVo.setOrganizationalName("总部");
        } else {
            Organizational oz = organizationalMapper.selectByPrimaryKey(deptID);
            if (oz == null) {
                traceabilityVo.setOpathName("总部");
                traceabilityVo.setOrganizationalName("总部");
            } else {
                String opathName = retOpathtName(oz);
                if (null != opathName && !"".equals(opathName)) {
                    traceabilityVo.setOpathName(opathName + "/" + oz.getOrganizationalName());
                } else {
                    traceabilityVo.setOpathName(oz.getOrganizationalName());
                }
                traceabilityVo.setOrganizationalName(oz.getOrganizationalName());
            }
        }

        return traceabilityVo;
    }

    /**
     * 获取组织架构路径
     *
     * @param orgVo
     * @return
     */
    private String retOpathtName(Organizational orgVo) {
        String pathName = null;
        switch (orgVo.getLevel()) {
            case 2:
                pathName = ("总部");
                break;
            case 3:
                Organizational oz = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                pathName = ("总部/" + oz.getOrganizationalName());
                break;
            case 4:
                Organizational oz1 = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                Organizational oz2 = organizationalMapper.selectByPrimaryKey(orgVo.getTwoLevelBranchID());
                pathName = ("总部/" + oz1.getOrganizationalName() + "/" + oz2.getOrganizationalName());
                break;
        }
        return pathName;
    }

    //根据userIDList查询对应的手机号
    public Object selectMobileByUserIDList(List<Long> userIDList) {
        List<Map<String, Object>> mobileList = userInfoMapper.selectMobileByUserIDList(userIDList);
        Map<String, Object> resultMap = new HashMap<>();
        if (mobileList.size() > 0) {
            for (Map<String, Object> map : mobileList) {
                resultMap.put(map.get("userID").toString(), map.get("mobile"));
            }
        }
        return resultMap;
    }

    //根据userID查询对应的系统管理员及其用户类型
    public Object selectAdminIDByUserID(Long userID) {
        Map<String, Object> param = new HashMap<>();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        Organizational organizational = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
        Long adminID = organizational.getAdminID();//修改查询管理员ID

        int type = 0;
        switch (userInfo.getType()) {
            case 1:
                type = 3;
                break;
            case 2:
                type = 2;
                break;
            case 3:
                type = 1;
                break;
            case 4:
                type = 1;
                break;
        }
        param.put("type", type);
        param.put("adminID", adminID);
        param.put("mobile", userInfo.getMobile());
        return param;
    }

    //查询角色信息userID
    private String getRoleName(Long userID) {
        List<UserRole> userRoleList = userRoleMapper.selectByUserID(userID);
        String roleName = "";
        if (userRoleList.size() > 0) {
            for (UserRole userRole : userRoleList) {
                Role role = roleService.selectByRoleID(userRole.getRoleID());
                if (role != null) {
                    if (userRoleList.size() == 1) {
                        roleName = role.getRoleName();
                    } else {
                        roleName += role.getRoleName() + " ";
                    }
                }
            }
        } else {
            roleName = "未查到角色名";
        }
        return roleName;
    }

    /**
     * //生成唯一不重复的推荐码
     *
     * @param type 1销售经理6位数，2销售顾问8位数
     * @return
     */
    private int getRecommendNO(int type) {
        int num = 0;
        switch (type) {
            case 1:
                num = 6;
                break;
            case 2:
                num = 8;
                break;
        }
        int code = RandomCodeUtils.getRandomCode(num);
        UserInfo userInfo = userInfoMapper.selectByRecommendNO(code, SystemContext.getCompanyID());
        if (userInfo != null) {
            return getRecommendNO(type);
        }
        return code;
    }

 /*   public static void main(String[] args) {
        System.out.println(RandomCodeUtils.getRandomCode(6));
    }*/

    /**
     * 获取今天零点的时间戳
     *
     * @param
     * @return
     */
    private Long getTimesamp() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }

    //理财经理注册送金豆  如果是员工送100克，如果是会员送100颗，并且推荐人也送100颗
    //update  2018-4-8
    public Object setManagerPoint(UserInfo userInfo) {
        if (configService.isOpenGoldPoint()) {
            if (userInfo.getType() == 2 || userInfo.getType() == 4) {
                registerPoint(userInfo);
                //会员推荐人送100颗
                if (userInfo.getType() == 4 && userInfo.getPaterID() != null) {
                    UserInfo paterUser = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                    if (paterUser != null) {
                        registerPoint(paterUser);
                    }
                }
            }
        }
        return "success";
    }

    private void registerPoint(UserInfo userInfo) {
        String userName = userInfo.getName() == null ? "1" : userInfo.getName();
        String url = ProConstants.setManagerPoin + userInfo.getUserID() + "/" + userName + "/" + userInfo.getMobile();
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
    }


    //地址用户银行卡信息
    public Long addUserBankCard(BankCard bankCard) {
        //List<BankCard> list = selectUserBankCardsByUserID(bankCard.getUserID());
        BankCard defaultCard = selectUserDefaultBankCardByUserID(bankCard.getUserID());
        if (defaultCard == null) {
            //新增为默认
            bankCard.setIsDefault(1);
        } else {
            //如果不止一个，并且新增为默认
            if (bankCard.getIsDefault() != null && bankCard.getIsDefault() == 1) {
                //默认地址只能一个
                bankCardMapper.updateNoDefaultByUserID(bankCard.getUserID());
            } else {
                bankCard.setIsDefault(0);
            }
        }
        bankCard.setId(IdGen.get().nextId());
        bankCard.setAddTime(CommonUtils.getCurTimestamp());
        bankCardMapper.insertSelective(bankCard);

        return bankCard.getId();
    }

    //修改用户银行卡信息
    public Object updateUserBankCard(BankCard bankCard) {
        bankCardMapper.updateByPrimaryKeySelective(bankCard);
        return bankCard;
    }

    //删除用户银行卡信息
    public Object deleteUserBankCard(Long id) {
        bankCardMapper.deleteByPrimaryKey(id);
        return "";
    }

    //设置默认用户银行卡信息
    public Object updateUserBankCardDefault(Long id) {
        BankCard ua = bankCardMapper.selectByPrimaryKey(id);
        if (ua == null) {
            throw new ServiceException("用户银行卡信息不存在.即指定的id不存在", RestConst.ErrorCode.SERVICE_FAIL);
        }

        bankCardMapper.updateNoDefaultByUserID(ua.getUserID());
        BankCard card = new BankCard();
        card.setId(id);
        card.setIsDefault(1);
        bankCardMapper.updateByPrimaryKeySelective(card);

        return bankCardMapper.selectByUserID(ua.getUserID());
    }

    //按id查询用户银行卡信息
    public BankCard selectUserBankCardByID(Long id) {
        return bankCardMapper.selectByPrimaryKey(id);
    }


    //按userid查询用户默认用户银行卡信息
    public BankCard selectUserDefaultBankCardByUserID(Long userID) {
        List<BankCard> list = bankCardMapper.selectByUserID(userID);
        for (BankCard card : list) {
            if (card.getIsDefault() != null && card.getIsDefault().intValue() == 1) {
                return card;
            }
        }
        return null;
    }


    //按userID查询用户银行卡信息
    public List<BankCard> selectUserBankCardsByUserID(Long userID) {
        return bankCardMapper.selectByUserID(userID);
    }


    //=======================================create by zll 2017/4/11 ===========================
    public Object getUserInfoDetails(List<Long> userIDs) {
        if (userIDs == null || userIDs.size() == 0) {
            return new HashMap<>();
        }
        List<Map<String, Object>> list = userInfoMapper.selectUserInfoListByIds(userIDs);
        //将查询出来的转化成userInfo
//        List<UserInfoMainVo> userInfoList = this.getUserInfoByMap(list);
        Map<Long, Object> resultMap = new HashMap<>();
        for (Map<String, Object> map : list) {
            System.out.println("***");
            if (map.get("organizationalID") != null && (!"0".equals(map.get("organizationalID"))) && (!"".equals(map.get("organizationalID")))) {
                Organizational org = organizationalMapper.selectByPrimaryKey((Long) map.get("organizationalID"));
                Map<String, String> orgMap = getOraInfoById(org);
                map.put("headerName", orgMap.get("headerName"));
                map.put("branchName", orgMap.get("branchName"));
                map.put("twoLevelBranchName", orgMap.get("twoLevelBranchName"));
                map.put("subbranchName", orgMap.get("subbranchName"));
                map.put("level", org.getLevel());
                resultMap.put((Long) map.get("userID"), map);
            }
        }
        return resultMap;
    }

    /**
     * 将查询出来的map转换成userinfo
     *
     * @param listMap
     * @return
     */
    public List<UserInfoMainVo> getUserInfoByMap(List<Map<String, Object>> listMap) {
        List<UserInfoMainVo> list = new ArrayList<>();
        //,mobile,name,type,organizationalID
        for (Map<String, Object> map : listMap) {
            UserInfoMainVo userInfoMainVo = new UserInfoMainVo();
            userInfoMainVo.setUserId((Long) map.get("userID"));
            userInfoMainVo.setName((String) map.get("name"));
            userInfoMainVo.setType((int) map.get("type"));
            userInfoMainVo.setOrganizationalId((Long) map.get("organizationalID"));
            list.add(userInfoMainVo);
        }
        return list;
    }


    //根据一个组织id得到这个组织的所有关系
    public Map<String, String> getOraInfoById(Organizational org) {
        System.out.println("=====");
        Map<String, String> map = new HashMap<>();
        int level = org.getLevel();
        switch (level) {
            case 1:
                map.put("headerName", org.getOrganizationalName());
                break;
            case 2:
                //分部
                map.put("headerName", "总部");
                map.put("branchName", org.getOrganizationalName());
                break;
            case 3:
                //二级分部
                map.put("headerName", "总部");
                map.put("branchName", (organizationalMapper.selectByPrimaryKey(org.getBranchID())).getOrganizationalName());
                map.put("twoLevelBranchName", org.getOrganizationalName());
                break;
            case 4:
                //支部
                map.put("headerName", "总部");
                map.put("branchName", (organizationalMapper.selectByPrimaryKey(org.getBranchID())).getOrganizationalName());
                map.put("twoLevelBranchName", (organizationalMapper.selectByPrimaryKey(org.getTwoLevelBranchID())).getOrganizationalName());
                map.put("subbranchName", org.getOrganizationalName());
                break;
            default:
                throw new ServiceException("有错误数据", RestConst.ErrorCode.DATABASE_ERROR);
        }

        return map;
    }


    /**
     * 得到所有的地址信息   ps:为了抛转以前的旧数据订单
     *
     * @return
     */
    public Object getAddressMap() {
        List<Map<String, Object>> list = userAddressMapper.getAddressMapByIds();
        Map<Long, Map<String, Object>> result = new HashMap<>();
        for (Map<String, Object> map : list) {
            result.put((Long) map.get("addressId"), map);
        }
        return result;
    }


    /*----------------------------维护订单以前的旧数据 create  by  zll-----------------------------------------------------*/
    public Object getMaintenanceData() {
        List<UpdateOrderVo> resultList = this.getOrgMaintenance();
        List<UpdateOrderVo> userList = this.getUserInfoMaintenance(SystemContext.getCompanyID());
        resultList.addAll(userList);
        System.out.println("抛转的组织以及人员信息是:" + resultList.size());
        return resultList;
    }


    public List<UpdateOrderVo> getUserInfoMaintenance(Long companyID) {
        List<Map<String, Object>> mapList = userInfoMapper.getOrderCountUserInfo(companyID);
        List<UpdateOrderVo> list = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            UpdateOrderVo vo = new UpdateOrderVo();
            Long level1 = (Long) map.get("level1");
            Long level2 = (Long) map.get("level2");
            Long level3 = (Long) map.get("level3");
            int type = (int) map.get("typeLevel");
            Long userId = (Long) map.get("userId");
            if (type == 1) {
                vo.setSalesManagerID(userId);
            } else if (type == 2) {
                vo.setBranchID(level1);
                vo.setSalesManagerID(userId);
            } else if (type == 3) {
                vo.setBranchID(level2);
                vo.setTwoLevelBranchID(level1);
                vo.setSalesManagerID(userId);
            } else if (type == 4) {
                vo.setBranchID(level2);
                vo.setTwoLevelBranchID(level3);
                vo.setSubbranchID(level1);
                vo.setSalesManagerID(userId);
            }
            list.add(vo);
        }
        return list;
    }

    public List<UpdateOrderVo> getOrgMaintenance() {

        List<Organizational> orgList = organizationalMapper.selectAllOrg(SystemContext.getCompanyID());
        List<UpdateOrderVo> list = new ArrayList<>();
        for (Organizational organizational : orgList) {
            UpdateOrderVo vo = new UpdateOrderVo();
            switch (organizational.getLevel()) {
                case 2:
                    vo.setBranchID(organizational.getoID());
                    break;
                case 3:
                    vo.setBranchID(organizational.getBranchID());
                    vo.setTwoLevelBranchID(organizational.getoID());
                    break;
                case 4:
                    vo.setBranchID(organizational.getBranchID());
                    vo.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                    vo.setSubbranchID(organizational.getoID());
                    break;
                default:
                    throw new ServiceException("有错误数据", RestConst.ErrorCode.FORM_FAIL);
            }
            list.add(vo);
        }
        return list;
    }

    /**
     * 模糊查询出一个组织下的员工
     *
     * @param organizationalId
     * @param searchName
     * @return
     */
    public Object getSaleManagerIDByName(Long organizationalId, String searchName) {
        Organizational organizational = organizationalMapper.selectByPrimaryKey(organizationalId);
        List<UserInfo> userInfos = userInfoMapper.selectByLikeName(searchName, organizational.getCompanyID());
        List<Long> resultList = new ArrayList<>();
        for (UserInfo user : userInfos) {
            Organizational org = organizationalMapper.selectByPrimaryKey(user.getOrganizationalID());
            if (organizational.getLevel() == 1) {
                resultList.add(user.getUserID());
            } else {
                if (org.getoID().compareTo(organizationalId) == 0 ||
                        (org.getBranchID() != null && organizationalId.compareTo(org.getBranchID()) == 0)
                        || (org.getTwoLevelBranchID() != null && organizationalId.compareTo(org.getTwoLevelBranchID()) == 0)) {
                    resultList.add(user.getUserID());
                }
            }
        }
        return resultList;
    }

    public UserInfo getRecommendNoByPaterID(Long paterID) {
        if (null == paterID || paterID <= 0)
            return null;
        return userInfoMapper.getRecommendNoByPaterID(paterID);
    }

    /**
     * 统计二级分部数量
     *
     * @param oID
     * @return
     */
    public Long countTwoLevelBranchNum(Long oID) {
        return organizationalMapper.countTwoLevelBranchNum(oID);
    }

    /**
     * 统计支部数量
     *
     * @param oID
     * @return
     */
    public Long countSubbranchNum(Integer level, Long oID) {
        return organizationalMapper.countSubbranchNum(level, oID);
    }


    /**
     * 统计员工激活数
     *
     * @return
     */
    public Long countEmployeeActNum(Integer level, Long oID) {
        Long total = 0l;
        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        switch (level) {
            case 0:
                total = userInfoMapper.countEmployeeActNumByoID(oID, organizational.getCompanyID());
                break;
            case 1:
                total = userInfoMapper.countEmployeeActNum(oID, organizational.getCompanyID());
                break;
            case 2:
                total = userInfoMapper.countEmployeeActNum_2(oID);
                break;
            case 3:
                total = userInfoMapper.countEmployeeActNum_3(oID);
                break;
        }
        return total;
    }

    /**
     * 分部员工
     * level 组织级别
     * levelNext
     *
     * @param level
     * @param branchID
     * @return
     */
    public List<UserOrganizationalInfoVo> branchEmployee(Integer level, Integer levelNext, Long branchID, Long companyID) {
        List<UserOrganizationalInfoVo> list = new ArrayList<UserOrganizationalInfoVo>();
        switch (level) {
            case 1:
                list = userInfoMapper.branchEmployee(level, levelNext, branchID, companyID);
                break;
            case 2:
                list = userInfoMapper.branchEmployee_2(level, levelNext, branchID);
                break;
            case 3:
                list = userInfoMapper.branchEmployee_3(level, levelNext, branchID);
                break;
        }
        return list;
    }

    /**
     * 分部会员
     *
     * @param level
     * @param branchID
     * @return
     */
    public List<UserOrganizationalInfoVo> branchMember(Integer level, Integer levelNext, Long branchID) {
        List<UserOrganizationalInfoVo> list = new ArrayList<UserOrganizationalInfoVo>();
        switch (level) {
            case 1:
                list = userInfoMapper.branchMember(level, levelNext, branchID);
                break;
            case 2:
                list = userInfoMapper.branchMember_2(level, levelNext, branchID);
                break;
            case 3:
                list = userInfoMapper.branchMember_3(level, levelNext, branchID);
                break;
        }
        return list;
    }

    /**
     * 统计理财经理的会员注册数
     *
     * @param oID
     * @return
     */
    public Long countMemberBySalesManager(Long oID) {
        return userInfoMapper.countMemberBySalesManager(oID);
    }


    public Map<String, Object> getAllEmpAndMemCount(Long companyID) {
        return userInfoMapper.getAllEmpAndMemCount(companyID);
    }

    public int updateByPrimaryKeySelective(UserInfo userInfo) {
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    public Object sys() {
        List<Count> list = countMapper.selectAll(null);
        for (Count count : list) {
            Long branchID = count.getBranchID();
            Long twoLevelBranchID = count.getTwoLevelBranchID();
            Long subbranchID = count.getSubbranchID();
            Long salesManagerID = count.getSalesManagerID();

            Long companyID = 0L;
            if (branchID != null && branchID != 0) {
                Organizational organizational = organizationalMapper.selectByPrimaryKey(branchID);
                if (organizational != null) {
                    companyID = organizational.getCompanyID();
                }

            } else if (twoLevelBranchID != null && twoLevelBranchID != 0) {
                Organizational organizational = organizationalMapper.selectByPrimaryKey(twoLevelBranchID);
                if (organizational != null) {
                    companyID = organizational.getCompanyID();
                }
            } else if (subbranchID != null && subbranchID != 0) {
                Organizational organizational = organizationalMapper.selectByPrimaryKey(subbranchID);
                if (organizational != null) {
                    companyID = organizational.getCompanyID();
                }
            } else if (salesManagerID != null && salesManagerID != 0) {
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(salesManagerID);
                if (userInfo != null) {
                    companyID = userInfo.getCompanyID();
                }
            }
            if (companyID != null && companyID != 0) {
                count.setCompanyID(companyID);
                countMapper.updateByPrimaryKeySelective(count);
            }

        }
        return "success";
    }

    /**
     * 定时任务审核三天未审核的部门调度
     */
    public Object handleExpiredTransfer() {
        List<UserInfo> users = userInfoMapper.selectExpiredTransfer();
        if (CollectionUtils.isNotEmpty(users)) {
            for (UserInfo userInfo : users) {
                userInfo.setState(1);
                userInfo.setIsStop(0);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
                userTransferService.checkUserTransferRecord(userInfo, false);
            }
        }
        return "success";
    }

    public String createToken(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        if (userInfo == null || !Objects.equal(userInfo.getCompanyID(), SystemContext.getCompanyID())) {
            throw new ServiceException("未知的用户");
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put(TokenConstants.userID, userID);
        map.put(TokenConstants.companyID, SystemContext.getCompanyID());
        map.put(TokenConstants.timestamp, System.currentTimeMillis() / 1000);
        return redisService.saveToken(map, userID);
    }

    public String getTokenFromRedis(Long userID) {
        return redisService.getToken(userID);
    }

    public String createToken(HttpServletRequest request) {
        String key = CommonTools.getGUID();
        Map<String, Object> map = Maps.newHashMap();
        map.put(TokenConstants.tkID, key);
        map.put(TokenConstants.ip, IpKit.getIpAddress(request));
        map.put(TokenConstants.timestamp, System.currentTimeMillis() / 1000);
        return redisService.saveToken(map, key);
    }

    public String initData(Integer type) {
        List<UserInfo> list = userInfoMapper.selectByType(type);
        for (UserInfo userInfo : list) {
            if (userInfo.getPaterID() == 0) {
                userInfo.setOrganizationalID(TopDeptEnum.valuekOf(userInfo.getCompanyID()).getDeptID());
            } else {
                UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(userInfo.getPaterID());
                if (userInfo1 != null) {
                    userInfo.setOrganizationalID(userInfo1.getOrganizationalID());
                } else {
                    logger.info("userInfo维护出错userID=" + userInfo.getUserID());
                }
            }
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        return "success";
    }

    public String getTokenFromRedis(String k) {
        return redisService.getToken(k);
    }

    public List<UserInfo> selAllUser(Long companyID) {
        return userInfoMapper.selAllUser(companyID);
    }

    public String getOpenImcs() {
        return openImcs;
    }

    public void setOpenImcs(String openImcs) {
        this.openImcs = openImcs;
    }


    public int initDataMember() {
        ResultData<Map<String, String>> data_ext = HttpUtil.httpGet_ResultData(ProConstants.BANKOPSSERVICE + "/sysConfig/selectAllExtByCID?companyInfoID=" + SystemContext.getCompanyID(), restTemplate);
        Map<String, String> ext = new HashMap<String, String>();
        if ("1".equals(data_ext.getCode())) {
            ext = data_ext.getData();
        }
        List<UserInfo> userInfos = userInfoMapper.selAllUser(SystemContext.getCompanyID());
        MemberDto[] memberDtos = new MemberDto[userInfos.size()];
        for (int i = 0; i < userInfos.size(); i++) {
            MemberDto memberDto = new MemberDto();
            memberDto.setMemberID(userInfos.get(i).getUserID() + "");
            memberDto.setShopID("0");
            memberDto.setName(userInfos.get(i).getName());
            memberDto.setPhone(userInfos.get(i).getMobile());
            memberDto.setNickname(userInfos.get(i).getNickName());
            memberDto.setSex(userInfos.get(i).getSex());
            memberDto.setBuildDate(userInfos.get(i).getAddTime());
            try {
                if (CommonUtils.isNotEmpty(userInfos.get(i).getBirthday())) {
                    memberDto.setBirthday(dateToStamp(userInfos.get(i).getBirthday()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            memberDto.setBirthdayType(0);
            memberDto.setSource(1);
            memberDto.setState(0);
            memberDto.setIntegral(0);
            memberDto.setIsJoint(1);
            memberDto.setAccountCode(ext.get(ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
            memberDtos[i] = memberDto;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("secretKey", ext.get(ErpInterfaceCfgEnum.SECRETKEY.getCode()));
        RestTemplate ts = new RestTemplate();
        ResponseEntity<ResultData> result = null;
        HttpEntity<MemberDto[]> entity = new HttpEntity<MemberDto[]>(memberDtos, headers);
        result = ts.exchange(ext.get(ErpInterfaceCfgEnum.MAINMEMBER.getCode()), HttpMethod.POST, entity, ResultData.class, "");
        ResultData res = result.getBody();
        String code = res.getCode();
        if ("1".equals(code)) {
            //成功
            System.out.println("初始化组织信息成功");
            return 1;
        } else {
            return 0;
        }

    }

    public int getUserGradeByUserID(Long userID) {
        List<Organizational> organizationals = organizationalMapper.selectByAdminID(userID);
        int grade = 9;
        if (CollectionUtils.isEmpty(organizationals)) {
            grade = 9;
        } else {
            //判断是否是省代管理者或加盟店管理者
            for (Organizational organizational : organizationals) {
                // 2一级代理 3二级分行 4三级代理
                if (Objects.equal(organizational.getLevel(), 2)) {
                    grade = 1;
                    break;
                }
                if (Objects.equal(organizational.getLevel(), 3)) {
                    grade = 2;
                    break;
                } else if (Objects.equal(organizational.getLevel(), 4)) {
                    grade = 3;
                    break;
                }
            }
        }
        return grade;
    }

    public Object getStoreManagerByUserID(Long userID) {
        Long storeManage = null;
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        Long shopID = userInfo.getShopID();
        if (shopID != null && !Objects.equal(shopID, 0l)) {
            CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(shopID);
            // List<UserInfo> userInfos = userInfoMapper.getShopManagerByShopID(shopID);
            if (companyInfo != null) {
                storeManage = companyInfo.getAdminID();
            }
        } else if (Objects.equal(userInfo.getType(), 2)) {
            Organizational org = organizationalMapper.selectByPrimaryKey(userInfo.getOrganizationalID());
            storeManage = org.getAdminID();
        }
        return storeManage == null ? 0 : storeManage;

    }
}
